and
, or
¶NOTES
paint_the_box.py
?while
/if
vs while
/while
waterfall.py
?and
¶take_cover.py
¶Move Bit to the first square blocked on either the left or the right side.
In other words: while both sides are clear, move the Bit.
%%file take_cover.py
from byubit import Bit
@Bit.run('take-cover', 'take-cover2')
def go(bit):
while bit.left_clear() and bit.right_clear():
bit.move()
or
¶%%file red_or_green.py
from byubit import Bit
@Bit.run('red-or-green')
def go(bit):
while bit.front_clear():
bit.move()
if bit.is_red() or bit.is_green():
bit.paint('blue')
and
, or
, and not
¶cross_the_pond.py
¶The green squares above blue are lilypads. They don't jump away as Bit passes by.
The red squares above black are flowers. They don't jump either.
The green squares above black is a frog. It will jump if Bit passes by.
Move Bit to the other side of the pond and clear the frogs.
%%file cross_the_pond.py
from byubit import Bit
@Bit.run('frog-on-rock')
def go(bit):
while bit.front_clear():
bit.move()
if bit.is_green() and not bit.right_clear():
bit.erase()
%%file to_freedom.py
from byubit import Bit
@Bit.run('freedom')
def go(bit):
while not (bit.left_clear() and bit.right_clear()):
bit.move()
When you hear
Move until condition is true
Think
while not condition:
bit.move()
NOTES
Strategy for composing a complex condition:
while not
in front of it# Solution
from byubit import Bit
@Bit.run('spiral')
@Bit.pictures('images/')
def run(bit):
bit.paint('blue')
while bit.front_clear() or bit.left_clear():
# Could also be: while not (not bit.front_clear() and not bit.left_clear()):
if not bit.front_clear():
bit.left()
bit.move()
bit.paint('blue')
# Another Solution
from byubit import Bit
@Bit.run('spiral')
def run(bit):
bit.paint('blue')
while bit.front_clear():
bit.move()
bit.paint('blue')
if not bit.front_clear() and bit.left_clear():
bit.left()
# Yet Another Solution (Mosaic)
from byubit import Bit
@Bit.run('spiral')
def run(bit):
bit.paint('blue')
bit.right()
while bit.left_clear():
bit.left()
while bit.front_clear():
bit.move()
bit.paint('blue')
# Yet Again Another Solution (Hybrid)
from byubit import Bit
@Bit.run('spiral')
def run(bit):
bit.paint('blue')
while bit.front_clear():
while bit.front_clear():
bit.move()
bit.paint('blue')
if bit.left_clear():
bit.left()
NOTES
Draw it out!
What pattern do we want to use? Mosaic? Event stream?
What ending condition do we use?
Solutions 1/2: Note how the loop body repeats a part of the loop condition (not bit.front_clear()
) and handles it, allowing the loop to continue.
Solution 2: using an if
at the end of the block that handles the event of running into an open corner
Solution 3: Note how we can do a little modification to the starting condition (bit.right()
) to make the whole problem a mosaic.
and
, or